package com.bianguo.android.baidumapdemo.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.search.core.TaxiInfo;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteLine;
import com.baidu.mapapi.search.route.MassTransitRouteLine.TransitStep;
import com.baidu.mapapi.search.route.MassTransitRoutePlanOption;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.baidu.mapapi.walknavi.WalkNavigateHelper;
import com.baidu.mapapi.walknavi.adapter.IWEngineInitListener;
import com.baidu.mapapi.walknavi.adapter.IWRoutePlanListener;
import com.baidu.mapapi.walknavi.adapter.IWTTSPlayer;
import com.baidu.mapapi.walknavi.model.WalkRoutePlanError;
import com.baidu.mapapi.walknavi.params.WalkNaviLaunchParam;
import com.bianguo.android.baidumapdemo.BaseActivity;
import com.bianguo.android.baidumapdemo.R;
import com.bianguo.android.baidumapdemo.adapter.InfoAdapter;
import com.bianguo.android.baidumapdemo.receiver.SMSReceiver;
import com.bianguo.android.baidumapdemo.service.LocationService;
import com.bianguo.android.baidumapdemo.utils.LocationHelper;
import com.bianguo.android.baidumapdemo.utils.MLog;
import com.bianguo.android.baidumapdemo.utils.PermissionHelper;
import com.bianguo.android.baidumapdemo.utils.PhoneUtil;
import com.bianguo.android.baidumapdemo.utils.WaveHelper;
import com.bianguo.android.baidumapdemo.widget.MyAF;
import com.bianguo.android.baidumapdemo.widget.SingerView;
import com.gelitenight.waveview.library.WaveView;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements SingerView.PaletteListener {

    @BindView(R.id.main_map)
    MapView mapView;
    @BindView(R.id.main_address)
    TextView addressTv;
    @BindView(R.id.main_palette)
    SingerView mPaletteView;

    public static final int REQUEST_CODE_SCANNING = 10001;
    public static final int REQUEST_CODE_ALBUM = 10002;
    private BaiduMap mBaiduMap;
    private LocationHelper mLocationHelper;
    private BottomSheetDialog mBottomDialog;
    private RoutePlanSearch mSearch;
    private SMSReceiver smsReceiver;
    private int mBorderColor = Color.parseColor("#44FFFFFF");
    private int mBorderWidth = 10;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private WaveHelper waveHelper;

    @Override
    protected int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(@Nullable Bundle saveInstanceState) {
        mBaiduMap = mapView.getMap();
        boolean permission = PermissionHelper.getInstance(mContext).isPermission(mContext, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PermissionHelper.PERMISSION_LOCATION);
        if (permission) {
            startLocation();
        }
        mPaletteView.setPaletteListener(this);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Bundle bundle = marker.getExtraInfo();
                int id = bundle.getInt("id", 0);
                MLog.mLog("markerId = " + marker.getId() + ", bundleId = " + id);
                if (mBottomDialog == null) {
                    mBottomDialog = new BottomSheetDialog(mContext);
                    View view = LayoutInflater.from(mContext).inflate(R.layout.bottom_dialog_info_layout, null);
                    RecyclerView mRecycler = (RecyclerView) view.findViewById(R.id.bottom_dialog_recycler);
                    ArrayList<String> list = new ArrayList<String>();
                    for (int i = 0; i < 20; i++) {
                        list.add("item --> " + (i + 1));
                    }
                    InfoAdapter infoAdapter = new InfoAdapter(mContext, list);
                    mRecycler.setAdapter(infoAdapter);
                    mBottomDialog.setContentView(view);
                }
                mBottomDialog.show();
                return false;
            }
        });

        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
                MLog.mLog("onGetWalkingRouteResult");
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
                MLog.mLog("onGetTransitRouteResult");
                List<TransitRouteLine> routeLines = transitRouteResult.getRouteLines();
                for (TransitRouteLine routeLine : routeLines) {
                }
            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
                MLog.mLog("onGetMassTransitRouteResult");
                TaxiInfo taxiInfo = massTransitRouteResult.getTaxiInfo();
                MLog.mLog("taxi price = " + taxiInfo.getTotalPrice() + ", perKMPrice = " + taxiInfo.getPerKMPrice() + ", startPrice = " + taxiInfo.getStartPrice() + ", distance = " + taxiInfo.getDistance());
                MLog.mLog("taxi desc = " + taxiInfo.getDesc() + ", duration = " + taxiInfo.getDuration() + ", totalLines = " + massTransitRouteResult.getTotal());
                List<MassTransitRouteLine> routeLines = massTransitRouteResult.getRouteLines();
                for (MassTransitRouteLine routeLine : routeLines) {
                    String arriveTime = routeLine.getArriveTime();
                    MLog.mLog("arriveTime = " + arriveTime + ", price = " + routeLine.getPrice() + "元");
                    List<List<TransitStep>> newSteps = routeLine.getNewSteps();
                    for (List<TransitStep> steps : newSteps) {
                        for (TransitStep step : steps) {
                            String instructions = step.getInstructions();
                            TransitStep.StepVehicleInfoType vehileType = step.getVehileType();
                            MLog.mLog("instructions = " + instructions + ", vehileType = " + vehileType.getInt());
                        }
                    }
                }
            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
                MLog.mLog("onGetDrivingRouteResult");
            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
                MLog.mLog("onGetIndoorRouteResult");
            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
                MLog.mLog("onGetBikingRouteResult");
            }
        });
        initXg();
        initReceiver();
        mHandler.sendEmptyMessageDelayed(40, 500);
    }

    private void initReceiver() {
        smsReceiver = new SMSReceiver();
        IntentFilter smsFilter = new IntentFilter();
        smsFilter.addAction(PhoneUtil.SEND_INTENT);
        smsFilter.addAction(PhoneUtil.DELIVER_INTENT);
        registerReceiver(smsReceiver, smsFilter);
    }

    private void initXg() {
        XGPushConfig.setHuaweiDebug(true);
        XGPushConfig.enableOtherPush(getApplicationContext(), true);
        XGPushConfig.setMiPushAppId(this, "2882303761517729804");
        XGPushConfig.setMiPushAppKey(this, "5281772996804");
        XGPushConfig.enableDebug(this, true);
        XGPushManager.registerPush(this, new XGIOperateCallback() {
            @Override
            public void onSuccess(Object data, int flag) {
                //token在设备卸载重装的时候有可能会变
                MLog.mLog("TPush 注册成功，设备token为：" + data);
            }

            @Override
            public void onFail(Object data, int errCode, String msg) {
                MLog.mLog("TPush 注册失败，错误码：" + errCode + ",错误信息：" + msg);
            }
        });
    }

    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivityForResult(intent, REQUEST_CODE_ALBUM);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick({R.id.main_address, R.id.main_btn, R.id.send_sms_btn, R.id.scanning_btn,
            R.id.bus_btn, R.id.walk_btn, R.id.bezier_btn, R.id.bezier_car_btn,
            R.id.heart_btn, R.id.walk_record_screen, R.id.my_palette_btn,
            R.id.web_btn})
    public void onClickBk(View view) {
        switch (view.getId()) {
            case R.id.main_btn:
                startActivity(new Intent(mContext, PaletteActivity.class));
//                mBaiduMap.clear();
//                if (View.VISIBLE == mPaletteView.getVisibility()) {
//                    mPaletteView.setVisibility(View.GONE);
//                    mPaletteView.reset();
//                } else {
//                    mPaletteView.setVisibility(View.VISIBLE);
//                    paletteShowAnim();
//                }
                break;
            case R.id.main_address:
//                LocationService.startLocService(mContext);
//                startActivity(new Intent(mContext, PaletteActivity.class));
                startLocation();
//                if (View.VISIBLE == mPaletteView.getVisibility()) {
//                    mPaletteView.setVisibility(View.GONE);
//                    mPaletteView.reset();
//                } else {
//                    mPaletteView.setVisibility(View.VISIBLE);
//                    paletteShowAnim();
//                }
                break;
            //发送短信
            case R.id.send_sms_btn:
                startActivity(new Intent(mContext, PanelActivity.class));
                boolean permission = PermissionHelper.getInstance(mContext).isPermission(mContext, new String[]{Manifest.permission.SEND_SMS}, PermissionHelper.PERMISSION_SMS);
                if (permission) {
                    PhoneUtil.sendSms(mContext, "15700064964", "我有一只小毛驴我从来都不骑，有一天我心血来潮带它去赶集！");
                }
                break;
            //扫描二维码
            case R.id.scanning_btn:
                boolean isPermission = PermissionHelper.getInstance(mContext).isPermission(mContext, new String[]{Manifest.permission.CAMERA}, PermissionHelper.PERMISSION_CAMERA);
                if (isPermission) {
                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCANNING);
                }
//                openAlbum();
                break;
            //公交查询
            case R.id.bus_btn:
                PlanNode stMassNode = PlanNode.withCityNameAndPlaceName("杭州", "蔚蓝国际");
                PlanNode enMassNode = PlanNode.withCityNameAndPlaceName("杭州", "打铁关地铁站");
//                mSearch.masstransitSearch(new MassTransitRoutePlanOption().from(stMassNode).to(enMassNode));
                mSearch.transitSearch(new TransitRoutePlanOption().city("杭州").from(stMassNode).to(enMassNode));
                break;
            //步行导航
            case R.id.walk_btn:
                if (true) {
                    initString(1, "", "", "");
                    return;
                }
                LatLng startPt = new LatLng(39.915291, 116.403857);
                LatLng endPt = new LatLng(40.056858, 116.308194);
                if (!PhoneUtil.checkAppExist(mContext, "com.baidu.BaiduMap")) {
                    NaviParaOption para = new NaviParaOption()
                            .startPoint(startPt).endPoint(endPt)
                            .startName("天安门").endName("百度大厦");
                    BaiduMapNavigation.openBaiduMapWalkNavi(para, this);
                } else {
                    final WalkNaviLaunchParam param = new WalkNaviLaunchParam().stPt(startPt).endPt(endPt);
                    // 获取导航控制类
                    final WalkNavigateHelper mNaviHelper = WalkNavigateHelper.getInstance();
                    mNaviHelper.initNaviEngine(this, new IWEngineInitListener() {
                        @Override
                        public void engineInitSuccess() {
                            MLog.mLog("引擎初始化成功");
                            mNaviHelper.routePlanWithParams(param, new IWRoutePlanListener() {
                                @Override
                                public void onRoutePlanStart() {
                                    MLog.mLog("开始算路");
                                }

                                @Override
                                public void onRoutePlanSuccess() {
                                    MLog.mLog("算路成功，跳转至诱导页面");
                                    startActivity(new Intent(mContext, WNaviGuideActivity.class));
                                }

                                @Override
                                public void onRoutePlanFail(WalkRoutePlanError walkRoutePlanError) {
                                    MLog.mLog("算路失败");
                                }
                            });
                        }

                        @Override
                        public void engineInitFail() {
                            MLog.mLog("引擎初始化失败");
                        }
                    });
                }
                break;
            case R.id.bezier_btn:
                startActivity(new Intent(mContext, BezierActivity.class));
                break;
            case R.id.bezier_car_btn:
                startActivity(new Intent(mContext, GoodsActivity.class));
                break;
            case R.id.heart_btn:
                startActivity(new Intent(mContext, HeartActivity.class));
                break;
            case R.id.walk_record_screen:
                ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(mContext, view, getResources().getString(R.string.share_element_record_screen));
                startActivity(new Intent(mContext, RecordScreenActivity.class ), optionsCompat.toBundle());
                break;
            case R.id.my_palette_btn:
                startActivity(new Intent(mContext, MPaletteActivity.class));
                break;
            case R.id.web_btn:
                startActivity(new Intent(mContext, WebActivity.class));
                break;
        }
    }


    private void initString(int temp, String str, String s1, String s2) {
        if (PhoneUtil.checkAppExist(mContext, "com.autonavi.minimap")) {//高德地图导航
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            Uri uri = Uri
                    .parse("androidamap://route?sourceApplication=softname&slat="
                            + 39.915291 + "&slon=" + 116.403857 + "&dlat=" + 40.056858 + "&dlon=" + 116.308194
                            + "&dname=" + "百度大厦" + "&dev=0&m=1" + "&t=2");
            intent.setData(uri);
            startActivity(intent);
        } else if (PhoneUtil.checkAppExist(mContext, "com.baidu.BaiduMap")) {//百度地图导航
            DaoHang(temp, str, s1, s2);
        } else {
            Toast.makeText(this, "请安装高德地图或百度地图后再次操作！", Toast.LENGTH_SHORT).show();
        }
    }

    private void DaoHang(int temp, String str, String s1, String s2) {
        String strName = null;
        if (temp == 0) {
            strName = "transit";
        } else if (temp == 1) {
            strName = "driving";
        } else if (temp == 2) {
            strName = "walking";
        }
        String baiduUrl = "intent://map/" +
                    "direction?origin=latlng:" + 39.915291 + "," +
                    116.403857 + "|name:你家，他家" + "&destination=" + "百度大厦" + "&mode=" + strName + "&src=fayuan" +
                    "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end";
        try {
            Intent intent = Intent.parseUri(baiduUrl, 0);
            startActivity(intent); //启动调用
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCANNING) {
            //处理扫描结果（在上界面显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    MLog.mLog("解析结果:" + result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    MLog.mLog("解析二维码失败");
                }
            }
        } else if (requestCode == REQUEST_CODE_ALBUM) {
            if (data != null) {
                Uri uri = data.getData();
                ContentResolver cr = getContentResolver();
                MLog.mLog("uri = " + uri);
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(cr, uri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PermissionHelper.PERMISSION_LOCATION:
                if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
                    startLocation();
                }
                break;
            case PermissionHelper.PERMISSION_CAMERA:
                if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCANNING);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

    private void paletteShowAnim() {
        TranslateAnimation animation = new TranslateAnimation(-mPaletteView.getWidth(), 0, 0, 0);
        animation.setDuration(1000);
        mPaletteView.setAnimation(animation);
        animation.start();
    }

    private void startLocation() {
        mBaiduMap.setMyLocationEnabled(true);
        mLocationHelper = LocationHelper.getInstance(mContext);
        mLocationHelper.startLocation(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                navigateTo(bdLocation);
                mLocationHelper.stopLocation();
            }
        });
    }

    private void navigateTo(BDLocation bdLocation) {
//        if (PhoneUtil.checkAppExist(mContext, "com.baidu.BaiduMap")) {
//            //移动APP调起Android百度地图方式举例
//            Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("baidumap://map/direction?origin=我的位置&;destination=下沙银泰"));
//            intent.setPackage("com.baidu.BaiduMap");
//            startActivity(intent); //启动调用
//        }
        MLog.mLog("locType = " + bdLocation.getLocType());
        mPaletteView.setVisibility(View.GONE);
        addressTv.setText(bdLocation.getAddrStr());
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);
        LatLng ll = new LatLng(bdLocation.getLatitude(),
                bdLocation.getLongitude());

        MyLocationData.Builder builder = new MyLocationData.Builder();
        builder.latitude(bdLocation.getLatitude());
        builder.longitude(bdLocation.getLongitude());
        MyLocationData data = builder.build();
        mBaiduMap.setMyLocationData(data);

        setMarker(bdLocation);

        MapStatus mapStatus = new MapStatus.Builder()
                .target(ll)
                .zoom(18)
                .build();
        MapStatusUpdate statusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
        mBaiduMap.animateMapStatus(statusUpdate);
    }

    /**
     * 添加marker
     */
    private void setMarker(BDLocation bdLocation) {
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.location);
        ArrayList<OverlayOptions> optionses = new ArrayList<>();
        //定义Maker坐标点
        LatLng point1 = new LatLng(bdLocation.getLatitude() + 0.0003632d, bdLocation.getLongitude() + 0.0003621d);
        Bundle bundle1 = new Bundle();
        bundle1.putInt("id", 0);
        //构建MarkerOption，用于在地图上添加Marker
        MarkerOptions option1 = new MarkerOptions()
                .position(point1)
                .title("title1")
                .extraInfo(bundle1)
                .icon(bitmap);

        //定义Maker坐标点
        LatLng point2 = new LatLng(bdLocation.getLatitude() + 0.000654d, bdLocation.getLongitude() + 0.000215d);
        Bundle bundle2 = new Bundle();
        bundle1.putInt("id", 1);
        //构建MarkerOption，用于在地图上添加Marker
        MarkerOptions option2 = new MarkerOptions()
                .position(point2)
                .title("title2")
                .extraInfo(bundle2)
                .icon(bitmap);
        //定义Maker坐标点
        LatLng point3 = new LatLng(bdLocation.getLatitude() + 0.001654d, bdLocation.getLongitude() + 0.001215d);
        Bundle bundle3 = new Bundle();
        bundle1.putInt("id", 2);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option3 = new TextOptions()
                .position(point3)
                .fontColor(Color.WHITE)
                .fontSize(24)
                .extraInfo(bundle3)
                .text("三塘竹苑")
                .bgColor(ActivityCompat.getColor(mContext, R.color.colorAccent));

        LatLng llCircle = new LatLng(bdLocation.getLatitude() + 0.001000d, bdLocation.getLongitude() + 0.000615d);
        OverlayOptions ooCircle = new CircleOptions()
                .fillColor(0x000000FF)
                .center(llCircle)
                .stroke(new Stroke(2, ActivityCompat.getColor(mContext, R.color.colorAccent)))
                .radius(100);
//        mBaiduMap.addOverlay(ooCircle);
        //在地图上添加Marker，并显示
        optionses.add(option1);
        optionses.add(option2);
        optionses.add(option3);
//        optionses.add(ooCircle);
        mBaiduMap.addOverlays(optionses);

//        LatLng lla = new LatLng(bdLocation.getLatitude() + 0.001340d, bdLocation.getLongitude() + 0.000215d);
//        BitmapDescriptor bd1 = getBitmapDescriptor();
//        MarkerOptions ooA = new MarkerOptions()
//                .position(lla)
//                .icon(bd1);
//
//        mBaiduMap.addOverlay(ooA);
    }

    private BitmapDescriptor getBitmapDescriptor() {
        BitmapDescriptor bttmap = null;
        View item_view = LayoutInflater.from(mContext).inflate(R.layout.activity_palette, null);

        bttmap = BitmapDescriptorFactory.fromView(item_view);
        return bttmap;

    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(smsReceiver);
        mSearch.destroy();
        mapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onStartDraw() {

    }

    @Override
    public void onDrawing() {

    }

    @Override
    public void onFinishDraw(ArrayList<Point> points, boolean isClose) {
//        mPaletteView.saveToGallery(System.currentTimeMillis() + ",jpeg", CacheUtil.CACHE_DIR, "some description", Bitmap.CompressFormat.JPEG, 80);
        int size = points.size();
        MLog.mLog("size = " + size);
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        final ArrayList<LatLng> latLngs = new ArrayList<>();
        Point firstPoint = points.get(0);
        for (int i = 0; i < size; i++) {
            Point point = points.get(i);
            LatLng latLng = mBaiduMap.getProjection().fromScreenLocation(point);
            builder.include(latLng);
            latLngs.add(latLng);
        }

        LatLngBounds bounds = builder.build();
//        定义Ground显示的图片
        BitmapDescriptor bdGround = getBitmapDescriptor();
//        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(mPaletteView.getChartBitmap());
//        BitmapDescriptor bdGround = BitmapDescriptorFactory
//                .fromResource(R.drawable.shp_circle);

//        定义Ground覆盖物选项
//        OverlayOptions ooGround = new GroundOverlayOptions()
//                .positionFromBounds(bounds)
//                .image(bdGround)
//                .transparency(0.8f);

//        OverlayOptions ooGround = null;
//        MLog.mLog("isClose = " + isClose);
//        if (isClose) {
//            //多边形
//            ooGround = new PolygonOptions()
//                    .points(latLngs)
//                    .stroke(new Stroke(40, ActivityCompat.getColor(mContext, R.color.colorCover)))
//                    .fillColor(ActivityCompat.getColor(mContext, R.color.colorCover));
//        } else {
//            //折线
//            ooGround = new PolylineOptions()
//                    .points(latLngs)
//                    .color(ActivityCompat.getColor(mContext, R.color.colorCover))
//                    .keepScale(true)
//                    .width(130);
//        }

        //弧线
//        OverlayOptions ooGround = new ArcOptions();

        //画圆
//        int size1 = latLngs.size();
//        for (int i = 0; i < size1; i++) {
//            OverlayOptions ooGround = new CircleOptions()
//                    .fillColor(0x000000FF)
//                    .center(latLngs.get(i))
//                    .stroke(new Stroke(1, ActivityCompat.getColor(mContext, R.color.colorCover)))
//                    .fillColor(ActivityCompat.getColor(mContext, R.color.colorCover))
//                    .radius(80);
//        }
//        int size1 = latLngs.size();
//        ArcOptions ooGround = new ArcOptions();
//        ooGround.points(latLngs.get(0), latLngs.get(size1 / 2), latLngs.get(size1 - 1));
//        ooGround.color(ActivityCompat.getColor(mContext, R.color.colorCover));
//        ooGround.width(100);
//        mBaiduMap.addOverlay(ooGround);
//        for (int i = 0; i < size1; i++) {
//            if (i % 2 == 0 && i + 2 < size1) {
//                ArcOptions ooGround = new ArcOptions();
//                ooGround.points(latLngs.get(i), latLngs.get(i + 1), latLngs.get(i + 2));
//                ooGround.color(ActivityCompat.getColor(mContext, R.color.colorCover));
//                ooGround.width(100);
//                mBaiduMap.addOverlay(ooGround);
//            }
//        }

        OverlayOptions ooGround = new PolygonOptions()
                .points(latLngs)
                .stroke(new Stroke(1, ActivityCompat.getColor(mContext, R.color.colorCover)))
                .zIndex(3)
                .fillColor(ActivityCompat.getColor(mContext, R.color.colorCover));
        mBaiduMap.addOverlay(ooGround);

//        BitmapDescriptor bitmap = BitmapDescriptorFactory
//                .fromResource(R.drawable.location);
//        int size1 = latLngs.size();
//        for (int i = 0; i < size1; i++) {
//            if (i % 8 == 0) {
//                OverlayOptions marker = new MarkerOptions()
//                        .position(latLngs.get(i))
//                        .title("marker")
//                        .icon(bitmap);
//                mBaiduMap.addOverlay(marker);
//            }
//        }
        mPaletteView.setVisibility(View.GONE);
        mPaletteView.reset();
    }
}
